package com.coderyeah.cosmetology.service.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.coderyeah.cosmetology.entity.User;
import com.coderyeah.cosmetology.mapper.UserMapper;
import com.coderyeah.cosmetology.service.UserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.coderyeah.cosmetology.util.HttpClientUtil;
import com.coderyeah.cosmetology.util.Result;
import com.coderyeah.cosmetology.util.ResultCode;
import com.sun.org.apache.regexp.internal.REUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.RequestBody;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author lqs
 * @since 2022-05-24
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;

    @Override
    public Result saveUser(@RequestBody User user) {
        String password = user.getPassword();
        String username = user.getUsername();
        String phone = user.getPhone();

        if (StrUtil.isBlank(password) || StrUtil.isBlank(username) || StrUtil.isBlank(phone)) {
            return new Result("909", "用户信息不能为空！", null);
        }

        //判断用户名是否重复
        if (isExist(username)) {
            return new Result(ResultCode.EXIST.getCode(), ResultCode.EXIST.getMsg(), null);
        }

        //将密码MD5加密
        String newPwd = DigestUtil.md5Hex(password);

        user.setPassword(newPwd);
        int insert = userMapper.insert(user);

        if (insert > 0) {
            return Result.success(user);
        } else {
            return Result.fail();
        }
    }

    private boolean isExist(String username) {
        boolean flag;
        LambdaQueryWrapper<User> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(User::getUsername, username);
        queryWrapper.last("limit 1");
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            flag = false;
        } else {
            flag = true;
        }
        return flag;
    }

    @Override
    public Result onLogin(String phone, String password, String code) {
        //判断是否为空
        if (StrUtil.isBlank(phone) || StrUtil.isBlank(password) || StrUtil.isBlank(code)) {
            return new Result(ResultCode.EMPTY.getCode(), ResultCode.EMPTY.getMsg(), null);
        }

        //查询用户
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPassword, DigestUtil.md5Hex(password));
        wrapper.eq(User::getPhone, phone);
        wrapper.last("limit 1");
        User user = userMapper.selectOne(wrapper);
        if (user == null) {
            return new Result(ResultCode.NO_EXIST.getCode(), ResultCode.NO_EXIST.getMsg(), null);
        }
        //用户存在
        String url = "https://api.weixin.qq.com/sns/jscode2session?appid=wx1af68ba3de16024d&secret=ea2acb96fba953437da958ee74d6750e&js_code=" + code + "&grant_type=authorization_code";
        String result = HttpClientUtil.doGet(url);
        System.out.println(result + " ===========");
        JSONObject jsonObject = JSONUtil.parseObj(result);
        String openid = (String) jsonObject.get("openid");
        String session_key = (String) jsonObject.get("session_key");
        String token = DigestUtil.md5Hex(openid + session_key);

        user.setOpenid(openid);
        user.setSessionkey(session_key);
        user.setToken(token);
        userMapper.updateById(user);
        return new Result(ResultCode.LOGIN.getCode(), ResultCode.LOGIN.getMsg(), user.getToken());
    }

    @Override
    public Result modifyPwd(String phone, String newPwd) {
        User user = queryUserByPhone(phone);
        if (user == null) {//用户不存在
            return new Result(ResultCode.NO_EXIST.getCode(), ResultCode.NO_EXIST.getMsg(), null);
        }
        user.setPassword(DigestUtil.md5Hex(newPwd));
        userMapper.updateById(user);
        return Result.success(null);
    }

    private User queryUserByPhone(String phone) {
        LambdaQueryWrapper<User> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(User::getPhone, phone);
        wrapper.last("limit 1");
        User user = userMapper.selectOne(wrapper);
        return user;
    }
}
